<?php

namespace app\api\controller;

use app\common\controller\Api;
use Exception;
use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class OrderRefund extends Api
{

    /**
     * Refund模型对象
     * @var \app\admin\model\order\Refund
     */
    protected $model = null;
    protected $orderModel = null;

    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Refund;
        $this->orderModel = new \app\admin\model\Order;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 售后申请
     * @return void
     */
    public function apply()
    {
        $params = $this->request->post();
        Db::startTrans();
        try {

            if ($params['refund_type'] == 1) {
                if (empty($params['express'])) {
                    throw new Exception('请输入快递名称');
                }
                if (empty($params['express_no'])) {
                    throw new Exception('请输入快递单号');
                }
            }

            $data = [
                'status' => 7,
                'apply_refund_time' => time(),
            ];
            $this->orderModel->save($data, ['id' => $params['order_id']]);
            $params['user_id'] = $this->auth->id;
            $params['status'] = 1;

            $this->model->allowField(true)->save($params);


            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交成功');
    }

    /**
     * 退款售后信息
     * @return void
     */
    public function info()
    {
        $params = $this->request->get();
        try {
            $data = $this->model->where('order_id', $params['order_id'])->find();
            $data['createtime_text'] = date('Y-m-d H:i:s', $data['createtime']);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('查询成功', $data);
    }

    public function check()
    {
        $params = $this->request->post();
        Db::startTrans();
        try {
            $data = [
                'check_refund_time' => time(),
            ];
            $this->orderModel->save($data, ['id' => $params['order_id']]);

            $refundInfo=[
                'status' => $params['status'],
            ];
            if($params['status'] == 2){
                $refundInfo['reason']=$params['reason'];
            }

            $this->model->allowField(true)->save($refundInfo,['order_id'=>$params['order_id']]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }


}






























